package dietAndroidClient;

import java.util.Calendar;
import java.util.GregorianCalendar;

import Alarm.NotificationStart;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.Toast;

import com.mnk.TCPsoketTest.R;

public class AddActivity extends Activity implements OnClickListener, OnTimeChangedListener, OnDateChangedListener, OnCheckedChangeListener {
	
	// Taejin Kim, 2011.10.12
	// Main, ADD, RANK 
	// 2011.10.17
	//ADD timepicker
	
	private String return_msg;
	private Button rankActivityButton;
	private Button calendarActivityButton;
	private Button mainActivityButton;
	private Button settingActivityButton;
	private Button registButton;
	private CheckBox alarmCheck;
	private Boolean checked;

	private GregorianCalendar mCalendar;
	private DatePicker mDate;
	private TimePicker mTime;

	private Spinner spinner;
	private Spinner spinnerWeek;
	private EditText goal;
	
	private final String GET_LIST= "SELECT * from alarm_info";
	
	private static final String ALARM_UPDATE0 =
		"UPDATE alarm_info SET checked=0 WHERE id=1;";
	
	private static final String ALARM_UPDATE1 =
		"UPDATE alarm_info SET checked=1 WHERE id=1;";
	
	
	String sports;
	String goalText;
	String startDate;
	String endDate;
	String dayOfWeek;
	
	Toast mToast;

	TextView et_startdate, et_enddate,et_time;;
		private int iYear, iMonth, iDay, iHour, iMinute;
		     static final int DATE_DIALOG_ID = 0;
		     static final int TIME_DIALOG_ID = 1;
		     View tempv;
		
	
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add);
    
    mCalendar=new GregorianCalendar();
  
    mainActivityButton = (Button) findViewById(R.id.button1);
    mainActivityButton.setOnClickListener(this);
    
    calendarActivityButton = (Button) findViewById(R.id.button2);
    calendarActivityButton.setOnClickListener(this);
   
    rankActivityButton = (Button) findViewById(R.id.button3);
    rankActivityButton.setOnClickListener(this);
    
    settingActivityButton = (Button) findViewById(R.id.button4);
    settingActivityButton.setOnClickListener(this);
    
    registButton = (Button)findViewById(R.id.button6);
    registButton.setOnClickListener(this);

    alarmCheck = (CheckBox)findViewById(R.id.checkBox02);
    getDbData();   //  get alarm checked 
    alarmCheck.setOnCheckedChangeListener(mAlarmCheckListener);
    
   
	mDate=(DatePicker)findViewById(R.id.date_picker);
  	mDate.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), this);
	mTime = (TimePicker)findViewById(R.id.time_picker);
	mTime.setCurrentHour(mCalendar.get(Calendar.HOUR_OF_DAY));
	mTime.setOnTimeChangedListener(this);

	Init();
    et_startdate.setOnClickListener(new OnClickListener(){
             public void onClick(View v) {
                    // TODO Auto-generated method stub
                    tempv = v;
                    showDialog(DATE_DIALOG_ID);
             }
     });
     et_enddate.setOnClickListener(new OnClickListener(){
             public void onClick(View v) {
                    // TODO Auto-generated method stub
                    tempv = v;
                    showDialog(DATE_DIALOG_ID);
             }
     });
    
        
  } //public void onCreate
 
	
  
  //onclick this
  @Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.button1:
			Intent main = new Intent(this, DietClient.class);
		    startActivity(main);
		    finish();
			break;
		case R.id.button2:
			Intent cal = new Intent(this, CalendarView.class);
		    startActivity(cal);
		    finish();
			break;
		case R.id.button3:
			Intent rank = new Intent(this, RankActivity.class);
			startActivity(rank);
			finish();
			break;
		case R.id.button4:
			Intent set = new Intent(this, SettingActivity.class);
			startActivity(set);
			finish();
			break;
		case R.id.button6:
//			String sports = spinner.getSelectedItem().toString();
			sports = null;
			switch(spinner.getSelectedItemPosition()) {
			case 0:
				sports = "턱걸이";
				break;
			case 1:
				sports = "윗몸일으키기";
				break;
			case 2:
				sports = "달리기";
				break;
			case 3:
				sports = "걷기";
				break;
			}
//				String dayOfWeek = spinnerWeek.getSelectedItem().toString();
			dayOfWeek = null;
			switch(spinnerWeek.getSelectedItemPosition()) {
			case 0:
				dayOfWeek = "1:1:1:1:1:1:1";
				break;
			case 1:
				dayOfWeek = "1:0:1:0:1:0:0";
				break;
			case 2:
				dayOfWeek = "0:1:0:1:0:1:0";
				break;
			case 3:
				dayOfWeek = "1:1:1:1:1:0:0";
				break;
			case 4:
				dayOfWeek = "0:0:0:0:0:1:1";
				break;
			}
			
			goalText = goal.getText().toString();
			startDate = et_startdate.getText().toString();
			endDate = et_enddate.getText().toString();
			
			// data input check
			if (goalText.equals("") || startDate.equals("") || endDate.equals("")){
				if (goalText.equals("")){
					mToast = Toast.makeText(AddActivity.this, "�대룞 �잛닔瑜��낅젰�섏꽭��", Toast.LENGTH_LONG);
				}else if(startDate.equals("")){
					mToast = Toast.makeText(AddActivity.this, "�대룞 �쒖옉�쇱쓣 �낅젰�섏꽭��", Toast.LENGTH_LONG);
				}else{
					mToast = Toast.makeText(AddActivity.this, "�대룞 醫낅즺�쇱쓣 �낅젰�섏꽭��", Toast.LENGTH_LONG);
				}
				
				mToast.show();
			}else{
				appendInitData();
			
			/*Log.i("[AddActivity]SPORTS", sports);
			Log.i("[AddActivity]DAYOFWEEK", dayOfWeek);
			Log.i("[AddActivity]GOAL", goalText);
			Log.i("[AddActivity]START DATE", startDate);
			Log.i("[AddActivity]END DATE", endDate);*/
			
			// Save user data to DB
	    	// id:password:phoneNumber
	    	/*TCPclient tp = new TCPclient("ADD" + ":" + getMyPhoneNumber() + ":" +
	    			sports + ":" +  goalText + ":" + 
	    			startDate + ":" + endDate + ":" + dayOfWeek);*/
			
			
	    	/*TCPclient tp = new TCPclient("ADD" + ":" + getMyPhoneNumber() + ":" +
	    			sports + ":" +  goalText + ":" + 
	    			startDate + ":" + endDate + ":" + dayOfWeek);
	    	
	    	tp.run();*/
			Intent _main = new Intent(this, DietClient.class);
			startActivity(_main);
			finish();
			}
			break;
			
		}
		
	} 
  
  
  public void Init()
  {
       et_startdate = (TextView)findViewById(R.id.ET_StartDate);
       et_enddate = (TextView)findViewById(R.id.ET_EndDate);
       goal = (EditText) findViewById(R.id.editText1);
       spinner = (Spinner) findViewById(R.id.spinner);
       spinnerWeek = (Spinner) findViewById(R.id.spinner2);
        
       final Calendar objTime = Calendar.getInstance();
       iYear = objTime.get(Calendar.YEAR);
       iMonth = objTime.get(Calendar.MONTH);
       iDay = objTime.get(Calendar.DAY_OF_MONTH);
       iHour = objTime.get(Calendar.HOUR_OF_DAY);
	   iMinute = objTime.get(Calendar.MINUTE);
	   
  }
  
  
 // alarm CheckedChangeListener
  private OnCheckedChangeListener mAlarmCheckListener = new OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			
			Log.d("checked", checked.toString());
			// check alarm_info
			if(checked==false && isChecked==true){
				checked = true;

				Intent intent = new Intent(AddActivity.this, RepeatingAlarm.class);
				PendingIntent sender = PendingIntent.getBroadcast(AddActivity.this, 0, intent, 0);
				
				AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
				am.setRepeating(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), 86400 * 1000, sender);
				
				if(mToast != null){
					mToast.cancel();
				}
				mToast = Toast.makeText(AddActivity.this,R.string.repeating_scheduled,Toast.LENGTH_LONG);
				mToast.show();
				
				appendAlarmData1();	
				    
			}else if(checked==true && isChecked == false){
				
				checked = false;
				Intent intent = new Intent(AddActivity.this, RepeatingAlarm.class);
				PendingIntent sender = PendingIntent.getBroadcast(AddActivity.this, 0, intent, 0);
				
				AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
				am.cancel(sender);
				
				if(mToast !=null){
					mToast.cancel();
				}
				mToast = Toast.makeText(AddActivity.this, R.string.repeating_unscheduled, Toast.LENGTH_LONG);
				mToast.show();
				appendAlarmData0();	
			}
		
		}
	}; // private OnCheckedChangeListener

  private void getDbData(){
		SQLiteDatabase db = null;
		Integer count = 0;
		if(db == null) {
			db = openOrCreateDatabase(
					"goal_table.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
		}
		
		Cursor c = db.rawQuery(GET_LIST, null);
		startManagingCursor(c);
	
		String temp = "1";
		while (c.moveToNext() && count < 2){
			if (c.getString(1).equals(temp)){
				Log.i("checked1",c.getString(1));
				alarmCheck.setChecked(true);
				checked=true;
			}else{
				Log.i("checked2",c.getString(1));
				alarmCheck.setChecked(false);
				checked=false;
				}
		}
	}

  protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, iYear, iMonth,
					iDay);
		}
		return null;
	}

  private void updateDisplay(TextView et)
  {
        et.setText(new StringBuilder().append(iYear).append("-")
               .append(iMonth + 1).append("-").append(iDay));
  }
  
  private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {                  
                   public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                      // TODO Auto-generated method stub
                      iYear = year;
                      iMonth = monthOfYear;
                      iDay = dayOfMonth;
                      if(tempv.getId() == R.id.ET_StartDate)
                      {
                            updateDisplay(et_startdate);
                      }
                      else
                      {
                            updateDisplay(et_enddate);
                      }
               }
        };
       
	// add goal_info
	private void appendInitData() throws SQLException {
		 Log.i("[AppendDatabase]", "Add Data to goal_info");
	        
	        SQLiteDatabase db = null;
	        
	        db = openOrCreateDatabase(
	                        "goal_table.db", Context.MODE_PRIVATE, null);
	        
	        ContentValues cvInsert = new ContentValues();
	        cvInsert.put( "sports", sports);
	        cvInsert.put( "goal", goalText );
	        cvInsert.put( "startDate", startDate);
	        cvInsert.put( "endDate", endDate);
	        cvInsert.put( "weeklyDate", dayOfWeek);
	        cvInsert.put( "archievement", "" );
	        db.insert( "goal_info", null, cvInsert);
	        
	        db.close();
	        Log.i("[AppendDatabase]", "Done Add Data to goal_info");
			
	}
	// add alarm_info(ALARM_UPDATE0)
	private void appendAlarmData0() throws SQLException {
		
        Log.i("[AppendDatabase]", "Add Data to alarm_info");
        
        SQLiteDatabase db1 = null;
        
        db1 = openOrCreateDatabase(
                        "goal_table.db", Context.MODE_PRIVATE, null);
        
        ContentValues cvInsert1 = new ContentValues();
        
        cvInsert1.put( "checked", checked);
        
        db1.execSQL(ALARM_UPDATE0);
 
        db1.close();
        Log.i("[AppendDatabase]", "Done Add Data to alarm_info");
	
	}
	// add alarm_info(ALARM_UPDATE1)
	private void appendAlarmData1() throws SQLException {
		
        Log.i("[AppendDatabase]", "Add Data to alarm_info");
        
        SQLiteDatabase db1 = null;
        
        db1 = openOrCreateDatabase(
                        "goal_table.db", Context.MODE_PRIVATE, null);
        
        ContentValues cvInsert1 = new ContentValues();
        
        cvInsert1.put( "checked", checked);
       
        db1.execSQL(ALARM_UPDATE1);

        db1.close();
        Log.i("[AppendDatabase]", "Done Add Data to alarm_info");
	
	}

	@Override
	public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
		// TODO Auto-generated method stub
		
		mCalendar.set(mDate.getYear(), mDate.getMonth(),mDate.getDayOfMonth(),hourOfDay,minute);
		Log.i("HelloAlarmActivity",mCalendar.getTime().toString());

	}

	@Override
	public void onDateChanged(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
		// TODO Auto-generated method stub
		
	}
	
}